package com.rongshu.sendmessage.view.bottomView;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.rongshu.sendmessage.R;
import com.rongshu.sendmessage.util.upData.UpdateManager;

import static android.view.View.GONE;

public class UpDataBottomDialog {
    private final int state;
    private final String webUrl;
    private View inflate;
    private Context mContext;
    private BottomSheetDialog bsd1;
    private View iv_close;
    private RelativeLayout re_webview;
    private WebView web_view;
    private DownloadListener downloadListener=new DownloadListener() {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition,
                                    String mimetype, long contentLength) {
//            Log.i("tag", "url="+url);
//
//            Log.i("tag", "userAgent="+userAgent);
//
//            Log.i("tag", "contentDisposition="+contentDisposition);
//
//            Log.i("tag", "mimetype="+mimetype);
//
//            Log.i("tag", "contentLength="+contentLength);
//
//            Uri uri = Uri.parse(url);
//
//            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
//
//            mContext.startActivity(intent);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                boolean hasInstallPermission = mContext.getPackageManager().canRequestPackageInstalls();
                if (!hasInstallPermission) {
                    startInstallPermissionSettingActivity();
                    return;
                }
            }
            udpate(url);

        }
    };
    /**
     * 跳转到设置-允许安装未知来源-页面
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startInstallPermissionSettingActivity() {
        //注意这个是8.0新API
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
    }


    public void udpate(String url){
        UpdateManager manager = new UpdateManager(mContext, mContext,url);
        // 检查软件更新
        manager.checkUpdate();
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                //启动服务
////                Intent service = new Intent(MainPageActivity.this,UpdateService.class);
////                startService(service);
//
//            }
//        }).start();
    }
    public UpDataBottomDialog(int state, String webUrl){
       this.state=state;
       this.webUrl=webUrl;
     }
    public View showDialog(Context context) {
        //自定义dialog显示布局
        inflate = LayoutInflater.from(context).inflate(R.layout.up_data_h5_pager, null);
        mContext=context;
        initView(inflate);
        //自定义dialog显示风格
        bsd1=new BottomSheetDialog(mContext);
        inflate.post(new Runnable() {
            @Override
            public void run() {
                BottomSheetBehavior behavior= BottomSheetBehavior.from(bsd1.findViewById(R.id.design_bottom_sheet));
                behavior.setHideable(false);//此处设置表示禁止BottomSheetBehavior的执行
            }
        });

        bsd1.setContentView(inflate);
        bsd1.getWindow().findViewById(R.id.design_bottom_sheet)
                .setBackgroundResource(android.R.color.transparent);
        bsd1.setCanceledOnTouchOutside(false);
//        bsd1.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);

        bsd1.show();
        bsd1.setCanceledOnTouchOutside(false);
        bsd1.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if(mdialogLinstner!=null){
                    mdialogLinstner.closeLinstner(10);
                }
            }
        });
//        bsd1.setOnKeyListener(new DialogInterface.OnKeyListener() {
//            @Override
//            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
//                if(mdialogLinstner!=null&&state==1){
//                    mdialogLinstner.closeLinstner(10);
//                }
//                return false;
//            }
//        });
        initWebView();
        return inflate;
    }
    public boolean isShow(){
        return bsd1.isShowing();
    }
    private void initView(View inflate) {
        re_webview =  inflate.findViewById(R.id.re_webview);
        web_view =  inflate.findViewById(R.id.web_view);
        iv_close =  inflate.findViewById(R.id.iv_close);
        if (state==1){
            iv_close.setVisibility(View.VISIBLE);
        }else{
            iv_close.setVisibility(GONE);
        }
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mdialogLinstner!=null&&state==1){
                    mdialogLinstner.closeLinstner(state);
                }
                bsd1.dismiss();
            }
        });
    }
    /**
     * 更新webView显示h5页面
     */
    private void initWebView() {
        web_view.getSettings().setDefaultTextEncodingName("UTF-8") ;
        web_view.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url == null) return false;
                if (url.startsWith("http:") || url.startsWith("https:") ){
                    view.loadUrl(url);
                    return false;
                }else{
                    try{
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(url));
                        mContext.startActivity(intent);
                    }catch (Exception e){
                        Toast.makeText(mContext, "暂无应用打开此链接", Toast.LENGTH_SHORT).show();
                    }
                    return true;
                }
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                // TODO Auto-generated method stub
                handler.proceed();// 接受所有网站的证书
            }
        });
        web_view.setDownloadListener(downloadListener);
        WebSettings webSettings = web_view.getSettings();
        webSettings.setJavaScriptEnabled(true);//允许使用js
        webSettings.setDomStorageEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//不使用缓存，只从网络获取数据.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        web_view.loadUrl(webUrl);
//        web_view.loadUrl("https://www.baidu.com");
    }
    public void setOnclickLisner(DialogCloseLinstner linstner) {
        mdialogLinstner=linstner;
    }
    DialogCloseLinstner mdialogLinstner;

    public interface DialogCloseLinstner{
        void closeLinstner(int status);
    }
}
